package io.unicorn.modules.progress.controller;

import com.alibaba.fastjson.JSONObject;
import io.unicorn.modules.progress.entity.ProgressSingleton;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("progress")
public class ProgressController {
    private static final long serialVersionUID = 1L;

    @RequestMapping("/list")
    protected void doGet(
            @RequestParam Map<String, Object> params,
            HttpServletRequest request,
            HttpServletResponse response) throws IOException {

        String id = request.getSession().getId();
        String filename = request.getParameter("filename");
        //使用sessionid + 文件名生成文件号，与上传的文件保持一致
        id = id + filename;
        Object size = ProgressSingleton.get(id + "Size");
        size = size == null ? 100 : size;
        Object progress = ProgressSingleton.get(id + "Progress");
        progress = progress == null ? 0 : progress;

        JSONObject json = new JSONObject();
        json.put("size", size);
        json.put("progress", progress);

        response.getWriter().print(json.toString());
    }
}
